<template>
    <PageCard class="margin0">
        <template>
            <div class="enterList" v-if="name='four'">
            <el-button class="ed-button ed_black-bottom ed-button36" style="cursor: pointer;margin-right: 10px;" @click="synchronizate"><svg-icon icon-class="synchronizate" />同步</el-button>
                <el-popover
                    placement="bottom"
                    title=""
                    ref="popoverRef"
                    trigger="click">
                    <div slot="">
                        <el-upload
                                class="avatar-uploader"
                                action=""
                                drag
                                accept=".xlsx"
                                :before-upload="beforeAvatarUpload"
                                :http-request="httpRequest"
                                :show-file-list="false">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">
                                <el-link icon="el-icon-download" type="primary" download="安防视频设备导入模板.xlsx" href="/template/安防视频设备导入模板.xlsx">安防视频设备导入模板</el-link>
                            </div>
                        </el-upload>
                    </div>
                    <el-button slot="reference"  class="ed-button ed_white_bottom marginRight8 ed-button36" v-has="'basic:member:import'"><i class="el-icon-download"></i>导入</el-button>
                </el-popover>
                <el-button class="ed-button ed_black-bottom ed-button36" @click="add()"><svg-icon icon-class="add-svg"/>新增</el-button>
            </div>
        </template>
        
        <ApiTable :api="tableApi" ref="table" :params="videoParams">
        <el-table-column :show-overflow-tooltip="true" prop="devicePlace" label="设备地点"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="name" label="设备名称"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="deviceId" label="设备序列号" ></el-table-column>
        <!-- <el-table-column :show-overflow-tooltip="true" prop="payDeviceFactory" label="厂家名称" ></el-table-column> -->
        <el-table-column :show-overflow-tooltip="true" prop="deviceType" label="设备类型" :formatter="setDeviceType" ></el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="操作">
            <template slot-scope="scope">
                <el-button class="ed-table-bottom ed_black_border" v-has="'basic:project:update'" @click="edit(scope.row)">编辑</el-button>
                <el-button class="ed-table-bottom ed_delete_border" v-has="'basic:project:config'" @click="del(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </ApiTable>
        <EdDialog ref="dialogRef" v-if="showVideoConfigure" :title="isUpdate ? '编辑视频配置' : '新增视频配置'" @close-dialog="closeDialog" @save-dialog="saveDialog">
            <el-form :model="editForm"  ref="ruleForm" label-position='right' label-width="auto">
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="设备地点：" prop="devicePlace" :rules="$validate.validates({required:true,msg:'请输入'})" >
                            <el-input v-model="editForm.devicePlace" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备名称：" prop="deviceId" :rules="$validate.validates({required:true,msg:'请选择'})" >
                            <EdSelect v-model="editForm.deviceId" ref="selectpatrol" :selectParams="deviceNameParams"  style="width:100%"></EdSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="设备序列号：" prop="deviceId" :rules="$validate.validates({required:true,msg:'请输入'})" >
                            <el-input v-model="editForm.deviceId" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="22">
                        <el-form-item label="厂家名称：" prop="payDeviceFactory" :rules="$validate.validates({required:true,msg:'请选择'})" >
                            <EdSelect v-model="editForm.payDeviceFactory" :selectParams="payDeviceFactoryParams" style="width:100%" :formatter="setFactoryType"  ></EdSelect>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="22">
                        <el-form-item label="设备类型：" prop="deviceType">
                            <EdSelect v-model="editForm.deviceType" :selectParams="deviceTypeParams" style="width:100%" :formatter="setDeviceType"></EdSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="22">
                        <el-form-item label="经纬度：" prop="">
                            <el-input style="width:40%" placeholder="请输入" v-model="editForm.longitude"></el-input>&nbsp;&nbsp;<el-input style="width:40%" v-model="editForm.latitude"  placeholder="请输入"></el-input>
                            <span class="colorMainTwo marginLeft8" @click="showMap">
                                <i ><svg-icon icon-class="map-svg" style="width: 24px;height: 24px;"/></i>
                                <!-- <span class="marginLeft2 cursorPointer">地图定位</span> -->
                            </span>
                        </el-form-item>
                    </el-col>
                </el-row>  
            </el-form>
        </EdDialog>
        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
        <ed-map ref="edMap" @setAddress="setAddress" :edMapObj="edMapObj"></ed-map>
    </PageCard>
    
</template>

<script>
import EdMap from "../../../../components/EdMap.vue";
import EdDialog from 'src/components/EdDialog.vue'
import Page from 'src/views/components/Page.vue';
import ApiTable from 'src/components/ApiTable.vue'
import PageCard from 'src/views/components/PageCard.vue'
import EdSelect from 'src/components/EdSelect.vue'
import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
import {getDictByCode} from "src/api/dictionaries";
import {videoList,deleteVideoList,addVideoList,showVideoList,batchImport, videoDeviceList,synchronizate} from '../api.js'
    export default {
  components: { Page,ApiTable,PageCard,EdSelect,EdConfirmDelete,EdDialog,EdMap},
        name: "videoConfigure",
        props:{
            showTitle:{
                type:Boolean,
                required: false,
                default:true
            },
        },
        data(){
            return{
                // 列表传的参数
                videoParams:{
                    villageId:'',
                    villageName:'',
                    orgId:this.$store.getters.vid,
                    page:1
                },
                confirmRow:'',
                isUpdate:false,
                showVideoConfigure:false,
                editForm:{
                    devicePlace:'',
                    deviceName:'',
                    name:'',
                    deviceId:'',
                    payDeviceFactory:'',
                    deviceType:'',
                    latitude:'',
                    longitude:'',
                    orgId:this.$store.getters.vid,
                    villageId:'',
                    villageName:'',

                },
                deviceNameParams:{
                    placeholder:"请选择",
                    options: [],
                    props: {label:"name", value:"deviceId"},
                    // disabled:true
                },
                deviceTypeParams:{
                    placeholder:"请选择",
                    options: [],
                    props: {label:"label", value:"value"}
                },
                edMapObj:{},
            }
        },
        mounted() {
            this.initDic()
            if(this.$route.query.villageId){
                this.videoParams.villageId = this.$route.query.villageId
                this.videoParams.villageName = this.$route.query.villageName
                this.$refs.table.load(1)
                // console.log('this.$refs.table',this.$refs.table);
            }
        },
        activated(){
            this.initDic()
            if(this.$route.query.villageId){
                this.videoParams.villageId = this.$route.query.villageId
                this.videoParams.villageName = this.$route.query.villageName
                this.$refs.table.load(1)
            }
        },
        deactivated() {
            this.editForm = {
                devicePlace:'',
                deviceName:'',
                name:'',
                deviceId:'',
                payDeviceFactory:'',
                deviceType:'',
                latitude:'',
                longitude:'',
                orgId:this.$store.getters.vid,
                villageId:'',
                villageName:'',
            }
            // this.$refs['dialogRef'].resetFields();
        },
        methods:{
            tableApi:videoList,
            initDic(){
                // 获取字典-设备名称
                getDictByCode("device_type").then(response => {
                    if(response.success) {
                        this.deviceTypeParams.options=response.data.items
                    }
                })
              
            },

            getqueryDeviceList(){
                let that = this
                videoDeviceList({villageId:this.$route.query.villageId}).then(res=>{
                    if(res.success){
                        let options = res.data.map(x=>{
                            if(x.vedioBinding && x.vedioBinding==1) {
                                // 这里设置 如果 vedioBinding==1 就禁用 
                                return {name:x.name,deviceId:x.deviceId,disabled:true}
                            }else{
                                return {name:x.name,deviceId:x.deviceId,disabled:false}
                            }
                        })
                        that.$set(that.deviceNameParams,'options', options)
                    }
                })
            },
            setFactoryType(row){
                let options = this.payDeviceFactoryParams.options.find(x => x.value == row.payDeviceFactory)
                return options ? options.label: ''
            },
            setDeviceType(row){
                let options = this.deviceTypeParams.options.find(x => x.value == row.deviceType)
                return options ? options.label : ''
            },
            setdeviceNameType(row){
                let options = this.deviceNameParams.options.find(x => x.deviceId == row.deviceId)
                return options ? options.label : ''
            },

            // 视频配置导入
            beforeAvatarUpload(file){
                const fileType = file.name.split('.');
                const fileDate = fileType.slice(-1);
                if (['xlsx'].indexOf(fileDate[0]) < 0) {
                    this.$message.error('仅支持文件格式：.xlsx');
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 30;
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 30MB!');
                }
                if(isLt2M){
                    this.upFile = new FormData();
                    this.upFile.append("file",file)
                    this.upFile.append("villageId", this.$route.query.villageId);
                    this.upFile.append("villageName", this.$route.query.villageName);
                    this.upFile.append("orgId",this.$store.getters.vid);
                    this.upFile.append("orgName",this.$store.getters.orgName)
                }
                return isLt2M;
            },
            httpRequest(){
                batchImport(this.upFile).then(response => {
                    if(response.code == 20000) {
                        this.$message.success({
                            message: '导入成功！',
                            duration: 2000,
                            center:true
                        });
                        this.$refs.table.load(1)
                    }
                    this.$refs.popoverRef.doClose()
                }).catch(()=>{
                    this.$refs.popoverRef.doClose()
                })
            },
            del(row){
                this.confirmRow = row;
                this.$refs.confirmDeleteRef.open("操作确认","是否执行此操作？","warning")
            },
            confirmDeleteTrue(){
                    deleteVideoList({deviceId:this.confirmRow.deviceId,id:this.confirmRow.id,villageId:this.$route.query.villageId}).then(response => {
                        if(response.success) {
                            this.$message.success({
                                message: '项目已删除成功！',
                                duration: 2000,
                                center:true
                            });
                            this.$nextTick(()=>{
                            this.$refs.table.load(1,10)
                            })
                        }
                    })
            },
            add(){
                this.showVideoConfigure = true
                this.getqueryDeviceList()

            },
            edit(row){
                this.isUpdate=true;
                this.showVideoConfigure = true
                this.getqueryDeviceList()
                showVideoList({deviceId:row.deviceId}).then(response=>{
                    if(response.success){
                        this.editForm.devicePlace = response.data.devicePlace
                        this.editForm.deviceName = response.data.deviceName
                        this.editForm.deviceId = response.data.deviceId
                        this.editForm.payDeviceFactory = response.data.payDeviceFactory
                        this.editForm.deviceType = response.data.deviceType
                        this.editForm.longitude = response.data.longitude
                        this.editForm.latitude = response.data.latitude
                    }
                })
            },
            closeDialog(){
                // 用dialog的组件一定要这么写，要不然下次点击的时候不弹框
                this.showVideoConfigure = false
                this.$refs.ruleForm.resetFields()
            },
            saveDialog(){
                this.editForm.villageId = this.$route.query.villageId
                this.editForm.villageName = this.$route.query.villageName
                this.editForm.deviceName =this.$refs.selectpatrol.$el.__vue__.selectedLabel
                   this.$refs.ruleForm.validate((valid)=>{
                        if(valid){
                            addVideoList(this.editForm).then(response => {
                                // debugger
                                if(response.success) {
                                    if(this.isUpdate=true){
                                        this.$message.success({
                                            message: '编辑视频配置成功！',
                                            duration: 2000,
                                            center:true
                                        });
                                    } else {
                                        this.$message.success({
                                        message: '新增视频配置成功！',
                                        duration: 2000,
                                        center:true
                                    });
                                    }
                                    this.showVideoConfigure = false
                                    this.$refs.dialogRef.loading  = false
                                    this.$refs.table.load(1)
                                    this.editForm = {
                                        devicePlace:'',
                                        deviceName:'',
                                        name:'',
                                        deviceId:'',
                                        payDeviceFactory:'',
                                        deviceType:'',
                                        latitude:'',
                                        longitude:'', 
                                        orgId:this.$store.getters.vid,
                                        villageId:'',
                                        villageName:'',
                                    }
                                }
                            }).catch( res => {
                                this.$refs.dialogRef.loading  = false
                            })
                        } else {
                            this.$refs.dialogRef.loading  = false
                        }
                })
            },
            showMap(){
                this.$refs.edMap.showMap()
            },
            setAddress(data){
                // this.form.address = data.address;
                this.editForm.longitude = data.lnglat.lng
                this.editForm.latitude = data.lnglat.lat
                // this.form.lngLat = data.lnglat.R + ',' +data.lnglat.Q;
                // this.$refs.ruleForm.validateField("")
            },
            synchronizate() {
            // 调同步的接口
            synchronizate({ villageId: this.$route.query.villageId }).then(response => {
                if (response.success) {
                    this.$message.success({
                        message: '设备同步成功！',
                        duration: 2000,
                        center: true
                    });
                    this.videoDeviceList()
                } else {
                    this.$message.success({
                        message: '设备同步失败！',
                        duration: 2000,
                        center: true
                    });
                }
            })
        }
        }
    }
</script>

<style lang="scss">
.enterList{
    margin-bottom: 15px;
    text-align: right;
}
:deep .el-form-item .el-form-item__content{
    // display: flex;
}
</style>